'use strict';

const Service = require('egg').Service;

class MaintainService extends Service {

  async myMaintain(query) {
    const { ctx, app } = this
    const { limit, page, data } = query;
    console.log(query);
    const { name } = ctx.state.user
    const Op = app.Sequelize.Op;
    let where = {}
    where.upt_act = { [Op.ne]: 'D' }
    if(name != '超级管理员') {
      where.handler = name
    }
    if (data) {
      where = {
        [Op.or]: [{ equip_num: data }, { name: data }, { status: data }, { handler: data }],
      }
    }
    try {
      return await ctx.model.Maintain.findAndCountAll({
        where,
        limit: parseInt(limit),
        offset: (page - 1) * limit
      })
    } catch (error) {
      console.log(error);
      return false
    }
  }
  async handleReceive(body) {
    const { ctx } = this
    // console.log(body);
    const { userid, name } = ctx.state.user
    body.handler = name
    body.report_time = body.created_at
    body.status = '已接单'
    body.created_id = userid
    body.updated_id = userid
    body.created_at = ctx.helper.formatTime(new Date())
    body.updated_at = ctx.helper.formatTime(new Date())
    let data = { status: '已接单' }
    try {
      return await ctx.model.Warranty.update(data, {
        where: { num: body.num }
      }) && await ctx.model.Maintain.create(body)
    } catch (error) {
      console.log(error);
      return false
    }
  }
  async myMaintainDelete(num) {
    const { ctx } = this
    const body = {
      upt_act: 'D',
      updated_at: ctx.helper.formatTime(new Date()),
      updated_id: ctx.state.user.userid,
    };
    try {
      return await ctx.model.Maintain.update(body, {
        where: { num },
      });
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  async myMaintainUpdate(body) {
    const { ctx } = this;
    const { userid } = ctx.state.user;
    body.updated_at = ctx.helper.formatTime(new Date());
    body.updated_id = userid;
    body.upt_act = 'U';
    let status = body.equip_status
    // console.log(status);
    try {
      return await ctx.model.transaction(async t => {
        await ctx.model.Maintain.update(body, {
          transaction: t,
          where: {
            num: body.num,
          },
        });
        await ctx.model.Warranty.update(body, {
          transaction: t,
          where: {
            num: body.num,
          },
        })
        await ctx.model.Manage.update({status:status}, {
          transaction: t,
          where: {
            num: body.equip_num,
          },
        })
        return true
      });
    } catch (error) {
      console.log(error);
      return false
    }
  }
}

module.exports = MaintainService;
